package day3.jdbc.dao.refactor;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import day1.dao.DaoException;
import utility.JdbcUtilsByMyDatasource;

public abstract class AbstractDao {
	
	public Object find(String sql,Object[] args){
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			con=JdbcUtilsByMyDatasource.getConnection();
			ps=con.prepareStatement(sql);
			if(args!=null){
				for(int j=0;j<args.length;j++){
					ps.setObject(j+1, args[j]);
				}
			}
			rs=ps.executeQuery();
			Object object=null;
			if(rs.next()){
				object=rowMapper(rs);
			}
			return object;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new DaoException(e);
		}finally{
			JdbcUtilsByMyDatasource.free(rs, ps, con);
		}
	}

	abstract protected Object rowMapper(ResultSet rs) ;

	public int update(String sql,Object[] args){
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		int i=0;
		try {
			conn=JdbcUtilsByMyDatasource.getConnection();
			ps=conn.prepareStatement(sql);
			if(args!=null){
				for(int j=0;j<args.length;j++){
					ps.setObject(j+1, args[j]);
				}
			}
			i=ps.executeUpdate();
			return i;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new DaoException(e);
		}finally{
			JdbcUtilsByMyDatasource.free(rs, ps, conn);
		}
	}
}
